package com.zt.job;

import com.zt.mapper.EmpMapper;
import com.zt.service.UploadService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @version 1.0
 * @description 说明
 * @package com.itheima.job
 */
@Component
@Slf4j
public class CleanImgJob {

    @Autowired
    private UploadService uploadService;

    @Autowired
    private EmpMapper empMapper;

    @Scheduled(cron = "0 0 0/1 * * ?")
    public void cleanOssImage() throws Exception {
        //1.查询oss上所有的图片
        Set<String> imgInOss = uploadService.list();
        imgInOss.forEach(System.out::println);
        //2.查询员工中所有的图片
        Set<String> imgInDB = empMapper.selectAllImage();
        imgInDB = imgInDB.stream().map(img -> img.replaceAll("https://wlcfile.oss-cn-shenzhen.aliyuncs.com/",""))
            .collect(Collectors.toSet());
        log.info("oss上共有{}张，数据库中有{}", imgInOss.size(), imgInDB.size());
        imgInDB.forEach(System.out::println);
        //3.oss-db, removeAll 从oss集合中删除imgInDB， imgInOss与imgInDB 都有的会被删除掉
        imgInOss.removeAll(imgInDB);
        log.info("需要删除的图片共有{}张",imgInOss.size());
        if(imgInOss.size() > 0) {
            // 调用oss删除
            uploadService.remove(imgInOss.stream().toList());
        }

    }
}
